package org.maps;

import java.util.Comparator;
import java.util.Iterator;

/**
 * Created by oler on 20.08.14.
 */
public class MyTreeMap implements MyMap {

    private static final boolean RED = false;
    private static final boolean BLACK = true;

    private transient SimpleEntry root = null;

    private final Comparator comparator;
    private int size = 0;

    public static class SimpleEntry implements MyMapEntry {

        Object key;
        Object value;

        SimpleEntry left = null;
        SimpleEntry right = null;
        SimpleEntry parent;

        boolean color = BLACK;

        SimpleEntry(Object key, Object value, SimpleEntry parent) {

            this.key = key;
            this.value = value;
            this.parent = parent;
        }

        @Override
        public Object getKey() {

            return key;
        }

        @Override
        public Object getValue() {

            return value;
        }

        @Override
        public Object setValue(Object value) {

            Object oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        @Override
        public boolean equals(Object o) {

            if (!(o instanceof MyMap.MyMapEntry)) {
                return false;
            }
            MyMap.MyMapEntry e = (MyMap.MyMapEntry) o;

            return e.getKey().equals(key) && e.getValue().equals(value);
        }

        @Override
        public int hashCode() {
            int keyHash = (key == null ? 0 : key.hashCode());
            int valueHash = (value == null ? 0 : value.hashCode());
            return keyHash ^ valueHash;
        }

        @Override
        public String toString() {
            return getKey() + "=" + getValue();
        }
    }

    private class EntryIterator implements Iterator<Object> {

        private static final String REMOVE_IS_NOT_SUPPORTED_EX
                = "Remove iterator's operation is not supported for MyTreeMap!";

        private final MyTreeMap treeMap;
        private boolean onStartPoint = true;

        SimpleEntry entry;

        EntryIterator(MyTreeMap treeMap) {
            this.treeMap = treeMap;
        }

        @Override
        public final boolean hasNext() {

            if (onStartPoint && treeMap.size() > 0) {
                return true;
            }
            return treeMap.successor(entry) != null;
        }

        final SimpleEntry nextEntry() {

            if (onStartPoint) {
                entry = treeMap.getFirstEntry();
                onStartPoint = false;
            } else {
                entry = treeMap.successor(entry);
            }

            return entry;
        }

        @Override
        public void remove() {

            throw new UnsupportedOperationException(REMOVE_IS_NOT_SUPPORTED_EX);
        }

        @Override
        public Object next() {
            return nextEntry();
        }
    }

    /**
     * constructs a new, empty treemap, using the natural
     * ordering of its keys
     */
    public MyTreeMap() {
        comparator = null;
    }

    /**
     * constructs a new, empty treemap, ordered according
     * to the given comparator
     */
    public MyTreeMap(Comparator comparator) {
        this.comparator = comparator;
    }

    @Override
    public void clear() {

        root = null;
        size = 0;
    }

    @Override
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }

    @Override
    public boolean containsValue(Object value) {

        for (SimpleEntry e = getFirstEntry(); e != null; e = successor(e)) {

            if (valEquals(value, e.value)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object get(Object key) {
        SimpleEntry p = getEntry(key);
        return (p == null ? null : p.value);
    }

    @Override
    public boolean isEmpty() {
        return size() == 0;
    }

    @Override
    public Object put(Object key, Object value) {

        SimpleEntry t = root;
        if (t == null) {

            root = new SimpleEntry(key, value, null);
            size = 1;
            return null;
        }

        int cmp;
        SimpleEntry parent;
        Comparator cpr = comparator;

        if (cpr != null) {
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0) {
                    t = t.left;
                } else if (cmp > 0) {
                    t = t.right;
                } else {
                    return t.setValue(value);
                }
            } while (t != null);
        } else {
            if (key == null) {
                throw new NullPointerException();
            }

            Comparable k = (Comparable) key;
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0) {
                    t = t.left;
                } else if (cmp > 0) {
                    t = t.right;
                } else {
                    return t.setValue(value);
                }
            } while (t != null);
        }

        SimpleEntry e = new SimpleEntry(key, value, parent);
        if (cmp < 0) {
            parent.left = e;
        } else {
            parent.right = e;
        }
        fixAfterInsertion(e);
        size++;

        return null;
    }

    @Override
    public Object remove(Object key) {

        SimpleEntry p = getEntry(key);
        if (p == null) {
            return null;
        }

        Object oldValue = p.value;
        deleteEntry(p);
        return oldValue;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator entryIterator() {

        return new EntryIterator(this);
    }

    final SimpleEntry getEntry(Object key) {

        if (comparator != null) {
            return getEntryUsingComparator(key);
        }
        if (key == null) {
            throw new NullPointerException();
        }

        Comparable k = (Comparable) key;
        SimpleEntry p = root;
        while (p != null) {
            int cmp = k.compareTo(p.key);
            if (cmp < 0) {
                p = p.left;
            } else if (cmp > 0) {
                p = p.right;
            } else {
                return p;
            }
        }
        return null;
    }

    final SimpleEntry getEntryUsingComparator(Object key) {

        Comparator cpr = comparator;

        if (cpr != null) {
            SimpleEntry p = root;
            while (p != null) {
                int cmp = cpr.compare(key, p.key);
                if (cmp < 0) {
                    p = p.left;
                } else if (cmp > 0) {
                    p = p.right;
                } else {
                    return p;
                }
            }
        }
        return null;
    }

    final SimpleEntry getFirstEntry() {

        SimpleEntry p = root;
        if (p != null) {
            while (p.left != null) {
                p = p.left;
            }
        }
        return p;
    }

    static SimpleEntry successor(SimpleEntry t) {

        if (t == null) {
            return null;
        } else if (t.right != null) {
            SimpleEntry p = t.right;
            while (p.left != null) {
                p = p.left;
            }
            return p;
        } else {
            SimpleEntry p = t.parent;
            SimpleEntry ch = t;
            while (p != null && ch == p.right) {
                ch = p;
                p = p.parent;
            }
            return p;
        }
    }

    static final boolean valEquals(Object o1, Object o2) {
        return (o1 == null ? o2 == null : o1.equals(o2));
    }

    final int compare(Object k1, Object k2) {
        return comparator == null ? ((Comparable) k1).compareTo(k2)
                : comparator.compare(k1, k2);
    }

    private void deleteEntry(SimpleEntry p) {

        size--;

        if (p.left != null && p.right != null) {
            SimpleEntry s = successor(p);
            p.key = s.key;
            p.value = s.value;
            p = s;
        }

        SimpleEntry replacement = (p.left != null ? p.left : p.right);

        if (replacement != null) {
            replacement.parent = p.parent;
            if (p.parent == null) {
                root = replacement;
            } else if (p == p.parent.left) {
                p.parent.left = replacement;
            } else {
                p.parent.right = replacement;
            }

            p.left = p.right = p.parent = null;

            if (p.color == BLACK) {
                fixAfterDeletion(replacement);
            }
        } else if (p.parent == null) { // return if we are the only node.
            root = null;
        } else { //  No children. Use self as phantom replacement and unlink.
            if (p.color == BLACK) {
                fixAfterDeletion(p);
            }

            if (p.parent != null) {
                if (p == p.parent.left) {
                    p.parent.left = null;
                } else if (p == p.parent.right) {
                    p.parent.right = null;
                }
                p.parent = null;
            }
        }
    }

    private void fixAfterInsertion(SimpleEntry x) {

        x.color = RED;

        while (x != null && x != root && x.parent.color == RED) {

            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {

                SimpleEntry y = rightOf(parentOf(parentOf(x)));
                if (colorOf(y) == RED) {
                    setColor(parentOf(x), BLACK);
                    setColor(y, BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    x = parentOf(parentOf(x));
                } else {
                    if (x == rightOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateLeft(x);
                    }
                    setColor(parentOf(x), BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    rotateRight(parentOf(parentOf(x)));
                }
            } else {
                SimpleEntry y = leftOf(parentOf(parentOf(x)));
                if (colorOf(y) == RED) {
                    setColor(parentOf(x), BLACK);
                    setColor(y, BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    x = parentOf(parentOf(x));
                } else {
                    if (x == leftOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateRight(x);
                    }
                    setColor(parentOf(x), BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    rotateLeft(parentOf(parentOf(x)));
                }
            }
        }
        root.color = BLACK;
    }

    private void fixAfterDeletion(SimpleEntry x) {

        while (x != root && colorOf(x) == BLACK) {
            if (x == leftOf(parentOf(x))) {
                SimpleEntry sib = rightOf(parentOf(x));

                if (colorOf(sib) == RED) {
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateLeft(parentOf(x));
                    sib = rightOf(parentOf(x));
                }

                if (colorOf(leftOf(sib)) == BLACK &&
                        colorOf(rightOf(sib)) == BLACK) {
                    setColor(sib, RED);
                    x = parentOf(x);
                } else {
                    if (colorOf(rightOf(sib)) == BLACK) {
                        setColor(leftOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateRight(sib);
                        sib = rightOf(parentOf(x));
                    }
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(rightOf(sib), BLACK);
                    rotateLeft(parentOf(x));
                    x = root;
                }
            } else { // symmetric
                SimpleEntry sib = leftOf(parentOf(x));

                if (colorOf(sib) == RED) {
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateRight(parentOf(x));
                    sib = leftOf(parentOf(x));
                }

                if (colorOf(rightOf(sib)) == BLACK &&
                        colorOf(leftOf(sib)) == BLACK) {
                    setColor(sib, RED);
                    x = parentOf(x);
                } else {
                    if (colorOf(leftOf(sib)) == BLACK) {
                        setColor(rightOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateLeft(sib);
                        sib = leftOf(parentOf(x));
                    }
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(leftOf(sib), BLACK);
                    rotateRight(parentOf(x));
                    x = root;
                }
            }
        }

        setColor(x, BLACK);
    }

    private void rotateLeft(SimpleEntry p) {

        if (p != null) {
            SimpleEntry r = p.right;
            p.right = r.left;
            if (r.left != null) {
                r.left.parent = p;
            }
            r.parent = p.parent;
            if (p.parent == null) {
                root = r;
            } else if (p.parent.left == p) {
                p.parent.left = r;
            } else {
                p.parent.right = r;
            }
            r.left = p;
            p.parent = r;
        }
    }

    private void rotateRight(SimpleEntry p) {
        if (p != null) {
            SimpleEntry l = p.left;
            p.left = l.right;
            if (l.right != null) {
                l.right.parent = p;
            }
            l.parent = p.parent;
            if (p.parent == null) {
                root = l;
            } else if (p.parent.right == p) {
                p.parent.right = l;
            } else {
                p.parent.left = l;
            }
            l.right = p;
            p.parent = l;
        }
    }

    private static void setColor(SimpleEntry p, boolean c) {
        if (p != null) {
            p.color = c;
        }
    }

    private static SimpleEntry parentOf(SimpleEntry p) {

        return (p == null ? null : p.parent);
    }

    private static SimpleEntry leftOf(SimpleEntry p) {

        return (p == null) ? null : p.left;
    }

    private static SimpleEntry rightOf(SimpleEntry p) {

        return (p == null) ? null : p.right;
    }

    private static boolean colorOf(SimpleEntry p) {

        return (p == null ? BLACK : p.color);
    }


}
